import { setUserData, getUserData, setLoginType, getLoginType, removeUser } from '@/utils/loginauth.js'
import ajax from '@/utils/ajax'
import API from '@/api'
import { resetRouter,constantRoutes } from '@/router'

const state = {
	user: getUserData(),
	loginType: getLoginType(),
	rolePermissions: [],
	openId: null,
}

const mutations = {
	// 用户信息
	SET_USER: (state, user) => {
		setUserData(user)
		state.user = user
	},
	// 登录类型，web或客户端
	SET_LOGIN_TYPE: (state, loginType) => {
		setLoginType(loginType)
		state.loginType = loginType
	},
	SET_ROLES: (state, roles) => {
		state.rolePermissions = roles
	},
	SET_OPENID: (state, openid) => {
		state.openId = openid
	},
}

const actions = {
	// 保存用户信息
	setUserAction({ commit }, user) {
		commit('SET_USER', user)
	},
	// 登录类型
	LoginTypeActon({ commit }, loginType) {
		commit('SET_LOGIN_TYPE', loginType)
	},
	// 设置用户角色权限
	getRolePermission({ commit }) {
		return new Promise((resolve, reject) => {
			// commit('SET_ROLES', resolve(constantRoutes))
			
			// resolve(constantRoutes)
			ajax.get({
				url: API.getUserMenu + getUserData().id,
				data: {},
				showLoading: false,
				success: (response) => {
					const resp = response.data
					if(resp){
					resp.forEach(ele=>{
            ele.action = ele.url;

          })
					}
					commit('SET_ROLES', resp)
					if (resp) {
						resolve(resp)
					} else {
						resolve([])
					}
				},
				error: (res) => {
					reject(res)
				},
			})
		})
	},
	// 获取openId
	getOpenId({ commit }, code) {
		return new Promise((resolve, reject) => {
			ajax.post({
				url: API.getOpenid,
				data: { code: code },
				showLoading: false,
				success: (response) => {
					console.log(response)
					const resp = response.data
					// errcode如果是0，代表已经授权过了
					if (resp.errcode == 0) {
						commit('SET_USER', resp.user)
						commit('LoginType', 'web')
					}
					commit('SET_OPENID', resp.openid)
					resolve(response)
				},
				error: (res) => {
					reject(res)
				},
			})
		})
	},
	// 退出登录
	logoutAction({ commit }) {
		commit('SET_ROLES', [])
		removeUser()
		resetRouter()
	},

	// remove token
	resetUser({ commit }) {
		return new Promise((resolve) => {
			commit('SET_ROLES', [])
			removeUser()
			resolve()
		})
	},
}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
}
